<script setup>
import { ref } from 'vue'
import { LocationFilled } from '@element-plus/icons-vue'
import { getCategoryService, publishProductService } from '@/api/product'
import address_edit from './components/address_edit.vue'
import {uploadFileService} from '@/api/upload'
import { useUserStore } from '@/stores/index';
// 创建仓库
const userStore = useUserStore()

// 校验表单数据
const formRef = ref(null)
// 表单数据收集
const formData = ref({
  title: '',
  description: '',
  userId:'',
  categoryId: '',
  coverImage:'',
  images:'',
  province: '省份',
  city: '城市',
  postType: '',
  price: 0,
})
// 重置表单数据
const resetFormData = () => {
  formData.value = {
    title: '',
    description: '',
    userId: '',
    categoryId: '',
    coverImage: '',
    images: '',
    province: '省份',
    city: '城市',
    postType: '',
    price: 0,
  }
  fileList.value = []  // 清空文件列表
  fileImages.value = [] // 清空上传图片数据
  dialogImageUrl.value = '' // 重置预览图片的URL
  dialogVisible.value = false // 关闭图片预览对话框
}

// 定义校验规则
const rules = {
  title: [
    { required: true, message: '请输入商品标题', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
  ]
  ,
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'blur' },
  ],
}
// 分类列表
const categoryList = ref([])

// 获取分类列表
const getCategory = async () => {
  const res = await getCategoryService()
  categoryList.value = res.data.data
}
getCategory()

// ================================== 上传图片相关的数据和方法 ==========================================
const fileList = ref([]); // 存放已选择的图片文件
const dialogImageUrl = ref(''); // 当前预览图片的URL
const dialogVisible = ref(false); // 控制图片预览对话框的显示/隐藏

// 处理图片预览
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

// 处理图片删除
const handleRemove = (file, newFileList) => {
  fileList.value = newFileList;
  // 更新fileImages队列
  fileImages.value = newFileList.map(item => item.raw);
};

// 处理文件选择变化
const handleChange = (file, newFileList) => {
  fileList.value = newFileList.map((item) => {
    // 为了实现本地预览，需要在文件对象中设置url
    if (!item.url) {
      item.url = URL.createObjectURL(item.raw);
    }
    return item;
  });
  // 更新fileImages队列
  fileImages.value = newFileList.map(item => item.raw);
};

// 处理超过最大选择数的情况
const handleExceed = () => {
  ElNotification({
    title: '错误',
    message: '最多只能选择5张图片',
    type: 'error'
  })
};
// =======================================================================================================



// ================================== 地图控件相关的数据和方法 ==========================================

const showDrawer = ref(false)

// 高德地图api前端的城市数据
const handleAddressUpdate = (changeAddress) => {
  if (changeAddress) {
    formData.value.province = changeAddress.regeocode.addressComponent.province
    formData.value.city = changeAddress.regeocode.addressComponent.city
  }
};
// ====================================================================================================

// ---------------------后端数据封装------------------------

// 向服务器上传的数据
const fileImages = ref([])

// 发布按钮的动作
const publishProduct = async () => {
  // 校验失败会自动提示
  await formRef.value.validate()
  const fileFD = new FormData()
  // 将文件数据添加到FormData中
  fileImages.value.forEach((file, index) => {
    fileFD.append(`file${index}`, file);
  })
  
  // 向服务器上传数据，接收后端穿回来的图片路径
  const res = await uploadFileService(fileFD)
  
  if (res) {
    // 解析返回的JSON数组
    const imagePaths = JSON.parse(res.data.data)

    // 设置封面图片为路径数组中的第一张
    formData.value.coverImage = imagePaths[0]
    // 如果imagePaths的长度大于1
    if (imagePaths.length > 1) {
      // 设置其他图片路径
      formData.value.images = JSON.stringify(imagePaths.slice(1))
    }else{
      formData.value.images = JSON.stringify(imagePaths)
    }
    

  }
  // 传递给后端
  formData.value.userId = userStore.id
  await publishProductService(formData.value)
  // 清除表单数据
  resetFormData()
  ElNotification({
    title: '成功',
    message: '发布成功',
    type: 'success'
  })
}

// ---------------------------------------------------------
</script>

<template>
  <div class="publish-container animate__animated animate__fadeInLeft">

    <!-- 页面标题 -->
    <div class="header">
      <span>发布闲置</span>
    </div>
    <!-- 发布内容编辑区域 -->
    <div class="publish-content-container">
      <div class="header-title" style="margin-top: 10px;margin-bottom: 10px;font-size: 18px">图片编辑</div>

      <el-form :model="formData" :rules="rules" ref="formRef">
        <!-- 图片上传 -->
        <div class="img-list">
          <el-form-item prop="images">
            <el-upload ref="upload" list-type="picture-card" :auto-upload="false" :file-list="fileList" :limit="5"
              :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-change="handleChange"
              :on-exceed="handleExceed" multiple>
              <div style="font-size: 16px; color: #9999b3">+ 添加优质图</div>
            </el-upload>
            <el-dialog v-model="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-form-item>
        </div>

        <!-- 商品标题和描述 -->
        <div class="push-content">
          <el-form-item prop="title">
            <el-input style="margin-top: 20px; height: 40px; width: 30vw; " v-model="formData.title" maxlength="20"
              show-word-limit type="text" placeholder="填写商品标题，可能会更容易卖出哦~" class="input-title" />
          </el-form-item>
          <el-form-item label-width="0" prop="description">
            <el-input style="margin-top: 10px; width: 50vw;" v-model="formData.description" :rows="5" maxlength="200"
              show-word-limit type="textarea" placeholder="描述下宝贝的品牌型号、货品来源..." class="input-content" />
          </el-form-item>
        </div>

        <!-- 选择分类 -->
        <div class="select-category">
          <el-form-item label="商品分类" prop="categoryId" style="width:200px;font-weight: 700;">
            <el-select v-model="formData.categoryId" placeholder="选择商品分类">
              <el-option v-for="item in categoryList" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div style="margin-left: 20px">
        <el-divider style="width: 100%" />
      </div>

      <!-- 发布设置 -->
      <div class="header-title" style="margin-top: 10px;margin-bottom: 10px;font-size: 18px">发布设置</div>
      <div class="setting">
        <el-form-item label="宝贝位置">
          <div style="cursor: pointer;font-weight:700" @click="showDrawer = true">
            <el-icon color="#ff2442" size="20px">
              <LocationFilled />
            </el-icon>
            {{ formData.province + " - " + formData.city }}
          </div>
        </el-form-item>

        <el-form-item label="发货方式" prop="postTupe">

          <div class="radio-item">
            <label for="postTupe0">邮寄</label>
            <input type="radio" id="postTupe0" value="0" v-model.number="formData.postType" required>
            <label for="postTupe1">自提</label>
            <input type="radio" id="postTupe1" value="1" v-model.number="formData.postType" required>
          </div>
        </el-form-item>

        <el-form-item label="价格">
          <el-input-number required controls-position="right" v-model="formData.price" :precision="2" :step="1"
            :min="0"></el-input-number>
        </el-form-item>

      </div>
      <!-- 发布or取消按钮 -->
      <div class="submit-cancel">
        <button @click="publishProduct" style="color: white; background-color: #ff2442;">发布</button>
        <button>取消</button>
      </div>
    </div>

    <!-- 编辑收货地址的抽屉区域 -->
    <el-dialog v-model="showDrawer" width="600" center align-center :show-close="false" style="border-radius: 15px;">
      <address_edit @updateAddress="handleAddressUpdate"></address_edit>
    </el-dialog>
  </div>
</template>

<style lang="less" scoped>

.animate__animated {
      animation-fill-mode: both;
      animation-duration: 0.5s;
    }
.publish-container {
  flex: 1;
  padding: 0px 4vw;

  .header {
    height: 40px;
    line-height: 40px;
    font-size: 22px;
    font-weight: 700;
    color: #ff2442;
    border-left: 10px solid #ff2442;
    padding-left: 5px;
  }

  .publish-content-container {
    padding: 10px 50px;
    .header-title {
      font-weight: 600;
    }

    .setting {
      margin-top: 20px;
      margin-left: 5px;


      .radio-item {
        width: 120px;
        font-size: 14px;
        color: #606266;
        display: flex;
        justify-content: space-evenly;
        align-items: center;
        input {
          margin-top: 3px;
          transition: all .2s;
          &:hover {
            cursor: pointer;
            transform: scale(1.3);
          }
        }
      }
    }

    .submit-cancel {
      margin-top: 20px;
      button {
        width: 80px;
        height: 40px;
        font-size: 16px;
        font-weight: 600;
        border-radius: 15px;
        margin-right: 30px;
        transition: all .2s;
        &:hover {
          cursor: pointer;
          transform: scale(1.08);
        }
      }
    }

    :deep(.el-input__inner) {
      font-weight: 700;
    }
    .address-edit-container{
      position: fixed;
    }
  }
}
</style>
